package city.spring.configure.authorization.translator;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 对登录时的错误进行序列化，按照指定的格式进行输出
 *
 * @author HouKunLin
 */
public class UserOAuth2ExceptionSerializer extends StdSerializer<UserOAuth2Exception> {
    private static final Logger logger = LoggerFactory.getLogger(UserOAuth2ExceptionSerializer.class);

    protected UserOAuth2ExceptionSerializer() {
        super(UserOAuth2Exception.class);
    }

    @Override
    public void serialize(UserOAuth2Exception e, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException {
        logger.debug("身份认证服务错误", e);
        Map<String, Object> jsonResult = new HashMap<>(8);
        jsonResult.put("msg", e.getMessage());
        jsonResult.put("code", e.getStatus().value());

        Map<String, String> additionalInformation = e.getAdditionalInformation();
        if (additionalInformation != null) {
            for (Map.Entry<String, String> entry : additionalInformation.entrySet()) {
                jsonResult.put(entry.getKey(), entry.getValue());
            }
        }
        generator.writeObject(jsonResult);
    }
}